package com.ruoyi.quartz.task;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.SyncConstants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.quartz.domain.*;
import com.ruoyi.quartz.service.ISyncDataErrSendService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Component("syncData2")
public class SyncData2 {
    private static final Logger log = LoggerFactory.getLogger(SyncData2.class);
    private  String orgId="66";
    private String username = "zhijijiankong";
    private String passwd = "WkpqazEyMyE=";


    @Autowired
    public ISyncDataErrSendService syncDataService;

    private List<OperatorInfo> operatorInfoList;

    public void getToken() {
        JSONObject param = new JSONObject();
        param.put("username", username);
        param.put("password", passwd);
        String res = HttpUtils.sendPost(SyncConstants.AUTH_URL, JSONObject.toJSONString(param));
        if (!StringUtils.isEmpty(res)) {
            JSONObject json = JSONObject.parseObject(res);
            if (Convert.toBool(json.get("loginStatus"))) {
                CacheUtils.put("token", json.get("token"));
            }
        }
    }
    /**
     * 整经报工
     */
    public JSONObject sysncZjWeavereport2Mes(WeaveReport weaveReport1) {
        List<WeaveReport> list = syncDataService.queryWeaveReportList(weaveReport1);
        List<User> userList = syncDataService.queryUserList("66");
        JSONObject json=new JSONObject();
        if (null != list && list.size() > 0) {
            log.info("开始发送整经报工数据，共：{}", list.size());
            for (int i = 0; i < list.size(); i++) {
                WeaveReport weaveReport = list.get(i);
                log.info("发送整经报工数据，共{}，第：{}条。{}", list.size(), i + 1, JSONObject.toJSONString(weaveReport));
                try {
                    if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                    weaveReport.operatorInfoList = new ArrayList<OperatorInfo>();
                    //添加整经人
                    for (User user : userList) {
                        if (user.getUserCode().equals(weaveReport.getZhengJingRen1())) {
                            OperatorInfo operatorInfo = new OperatorInfo();

                            double eAttribute27 = weaveReport.getEAttribute27() == "" ? 0 : Double.parseDouble(weaveReport.getEAttribute27());
                            operatorInfo.setQuantity(eAttribute27);//整经人1 产量

                            operatorInfo.setTeamName(weaveReport.EAttribute26);//整经人1 班组
                            operatorInfo.setTeamShift(weaveReport.EAttribute66);//整经人1 班次
                            operatorInfo.setOperatorAccount(weaveReport.getZhengJingRen1());//整经人1  账号
                            weaveReport.operatorInfoList.add(operatorInfo);
                        }
                        if (user.getUserCode().equals(weaveReport.getZhengJingRen2())) {
                            OperatorInfo operatorInfo1 = new OperatorInfo();
                            double eAttribute36 = weaveReport.getEAttribute36() == "" ? 0 : Double.parseDouble(weaveReport.getEAttribute36());
                            operatorInfo1.setQuantity(eAttribute36);//整经人2 产量
                            operatorInfo1.setTeamName(weaveReport.EAttribute35);//整经人2 班组
                            operatorInfo1.setTeamShift(weaveReport.EAttribute50); //整经人2  班次
                            operatorInfo1.setOperatorAccount(weaveReport.getZhengJingRen2()); //整经人2 账号
                            weaveReport.operatorInfoList.add(operatorInfo1);
                        }
                    }
                    if (weaveReport.operatorInfoList.size() == 0) {
                        return null;
                    }
                    String res = HttpUtils.yqs_sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_ZJ_URL, JSONObject.toJSONString(weaveReport), Convert.toStr(CacheUtils.get("token")));
                    if (!StringUtils.isEmpty(res)) {
                        json = JSONObject.parseObject(res);
                        SendMessageErr err = new SendMessageErr();
                        err.setStatus(json.get("state").toString());
                        err.setBillNo(weaveReport.getSerialNo());
                        err.setErrMessage(json.get("message").toString());
                        err.setMethod("sysncZjWeavereport2Mes");
                        err.setSendNode("整经报工");
                        if (Convert.toBool(json.get("state"))) {
                            log.info("发送整经报工数据成功，共{}，第：{}条。{}", list.size(), i, res);
                            syncDataService.isExistUpdate(err);
                            syncDataService.updateWeaveReport(weaveReport);
                        } else {
                            weaveReport.paramsArgs = json.get("message").toString();
                            syncDataService.updateWeaveReport_N(weaveReport);
                            syncDataService.isExistUpdateAndAdd(err);
                            log.info("发送整经报工数据失败，共{}，第：{}条。{}", list.size(), i, res);
                        }
                    } else {
                        log.info("调用整经报工接口失败，共{}，第：{}条。{}", list.size(), i, res);
                    }
                } catch (Exception e) {
                    log.info("发送整经报工数据失败，共{}，第：{}条。{}", list.size(), i, e);
                }
            }
            log.info("结束发送整经报工数据，共：{}", list.size());
        } else {
            log.info("没有需要同步的整经数据");
        }
        return json;
    }
    /**
     * 浆纱报工
     */
    public JSONObject syncJsWeavereport2Mes(WeaveJs weaveJs1) {
        List<WeaveJs> list = syncDataService.queryWeaveJsList(weaveJs1);
        List<User> userList = syncDataService.queryUserList("66");
        JSONObject json=new JSONObject();
        if (null != list && list.size() > 0) {
            log.info("开始发送浆纱报工数据，共：{}", list.size());

            for (int i = 0; i < list.size(); i++) {
                WeaveJs weaveJs = list.get(i);
                weaveJs.operatorInfoList = new ArrayList<OperatorInfo>();

                log.info("发送浆纱报工数据，共{}，第：{}条。{}", list.size(), i, JSONObject.toJSONString(weaveJs));
                try {
                    for (User user : userList) {
                        if (user.getUserCode().equals(weaveJs.reporterAccount)) {
                            OperatorInfo operatorInfo = new OperatorInfo();
                            operatorInfo.setOperatorAccount(weaveJs.reporterAccount);
                            operatorInfo.setTeamName(weaveJs.banZu);
                            weaveJs.operatorInfoList.add(operatorInfo);
                        }
                    }
                    if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                    String res = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_JS_URL, JSONObject.toJSONString(weaveJs), Convert.toStr(CacheUtils.get("token")));
                    if (!StringUtils.isEmpty(res)) {
                        json = JSONObject.parseObject(res);
                        SendMessageErr err = new SendMessageErr();
                        err.setStatus(json.get("state").toString());
                        err.setBillNo(weaveJs.getSerialNo());
                        err.setErrMessage(json.get("message").toString());
                        err.setMethod("syncJsWeavereport2Mes");
                        err.setSendNode("浆纱报工");
                        weaveJs.SyncMessage = res + JSONObject.toJSONString(weaveJs);
                        if (Convert.toBool(json.get("state"))) {
                            log.info("发送浆纱报工数据成功，共{}，第：{}条。{}", list.size(), i, res);
                            weaveJs.SyncMessage = "[浆纱]"+json.get("message").toString();
                            syncDataService.updateWeaveJs(weaveJs);
                            syncDataService.isExistUpdate(err);

                        } else {
                            log.info("发送浆纱报工数据失败，共{}，第：{}条。{}", list.size(), i, res);
                            log.info("异常参数{}", JSONObject.toJSONString(weaveJs));
                            weaveJs.SyncMessage = "[浆纱]"+json.get("message").toString();

                            syncDataService.isExistUpdateAndAdd(err);
                            syncDataService.updateWeaveJs_N(weaveJs);
                        }
                    } else {
                        log.info("调用浆纱报工接口失败，共{}，第：{}条。{}", list.size(), i, res);
                    }
                } catch (Exception e) {
                    log.info("发送浆纱报工数据失败，共{}，第：{}条。{}", list.size(), i, e);
                }
            }
            log.info("结束发送浆纱报工数据，共：{}", list.size());
        } else {
            log.info("没有需要同步的浆纱数据");
        }
        return json;
    }
    /**
     * 上轴报工
     */
    public JSONObject syncSzWeavereport2Mes(WeaveSz weaveSz1) {
        List<WeaveSz> list = syncDataService.queryWeaveSzList(weaveSz1);
        List<User> userList = syncDataService.queryUserList("66");
        JSONObject json = new JSONObject();
        if (null != list && list.size() > 0) {
            log.info("开始发送上轴报工数据，共：{}", list.size());
            for (int i = 0; i < list.size(); i++) {
                WeaveSz weaveSz = list.get(i);
                try {
                    List<OperatorInfo> operatorInfo = new ArrayList<OperatorInfo>();
                    if (weaveSz.getDengJiRen() != null) {
                        String[] split = weaveSz.getDengJiRen().split(";");
                        for (User user : userList) {
                            for (int n = 0; n < split.length; n++) {
                                if (user.getUserCode().equals(split[n])) {
                                    OperatorInfo operatorInfo1 = new OperatorInfo();
                                    operatorInfo1.setQuantity(0.0);
                                    operatorInfo1.setTeamName(weaveSz.banZu);
                                    operatorInfo1.setTeamShift("");
                                    operatorInfo1.setOperatorAccount(split[n]);
                                    operatorInfo.add(operatorInfo1);
                                }
                            }
                        }
                    }
                    weaveSz.setOperatorInfoList(operatorInfo);
                    log.info("发送上轴报工数据，共{}，第：{}条。{}", list.size(), i, JSONObject.toJSONString(weaveSz));
                    try {
                        if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                        String res = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_SZ_URL, JSONObject.toJSONString(weaveSz), Convert.toStr(CacheUtils.get("token")));
                        if (!StringUtils.isEmpty(res)) {
                            json = JSONObject.parseObject(res);
                            SendMessageErr err = new SendMessageErr();
                            err.setStatus(json.get("state").toString());
                            err.setBillNo(weaveSz.getSerialNo());
                            err.setErrMessage(json.get("message").toString());
                            err.setMethod("syncSzWeavereport2Mes");
                            err.setSendNode("上轴报工");
                            if (Convert.toBool(json.get("state"))) {
                                log.info("发送上轴报工数据成功，共{}，第：{}条。{}", list.size(), i, res);
                                syncDataService.updateWeaveSz(weaveSz);
                                syncDataService.isExistUpdate(err);
                            } else {
                                log.info("发送上轴报工数据失败，共{}，第：{}条。{}", list.size(), i, res);
                                weaveSz.SyncMessage = "[上轴]"+json.get("message").toString();
                                syncDataService.updateWeaveSz_N(weaveSz);
                                syncDataService.isExistUpdateAndAdd(err);
                            }
                        } else {
                            log.info("调用上轴报工接口失败，共{}，第：{}条。{}", list.size(), i, res);
                        }
                    } catch (Exception e) {
                        log.info("发送上轴报工数据失败，共{}，第：{}条。{}", list.size(), i, e);
                    }
                } catch (Exception e) {
                    log.info("上轴报工:{}", JSONObject.toJSONString(weaveSz));
                }

                WeaveReport reportZj = new WeaveReport();
                reportZj.setOrgId("66");

                reportZj.setSerialNo(weaveSz.getSerialNo());
                reportZj.setWarpBeamStatus("1");
                sysncZjWeavereport2Mes(reportZj);
            }
            log.info("结束发送上轴报工数据，共：{}", list.size());
        } else {
            log.info("没有需要同步的上轴数据");
        }
        return json;
    }
    /**
     * 开织报工
     */
    public JSONObject syncKzWeavereport2Mes(WeaveKz weaveKz1) {
        List<WeaveKz> list = syncDataService.queryWeaveKzList(weaveKz1);
        List<User> userList = syncDataService.queryUserList("66");
        JSONObject json = new JSONObject();
        if (null != list && list.size() > 0) {
            log.info("开始发送开织报工数据，共：{}", list.size());
            for (int i = 0; i < list.size(); i++) {
                WeaveKz weaveKz = list.get(i);

                if (weaveKz.getDengJiRen() != null) {
                    String[] split = weaveKz.getDengJiRen().split(";");
                    ArrayList<OperatorInfo> operatorInfos = new ArrayList<OperatorInfo>();
                    for (User user : userList) {
                        for (int t = 0; t < split.length; t++) {
                            if (user.getUserCode().equals(split[t])) {
                                OperatorInfo operatorInfo = new OperatorInfo();
                                operatorInfo.setOperatorAccount(split[t]);
                                operatorInfo.setTeamName(weaveKz.getBanZu());
                                log.info("====" + JSONObject.toJSONString(operatorInfo));
                                operatorInfos.add(operatorInfo);
                            }
                        }
                    }
                    weaveKz.setOperatorInfoList(operatorInfos);
                }

                log.info("发送开织报工数据，共{}，第：{}条。{}", list.size(), i, JSONObject.toJSONString(weaveKz));
                try {
                    if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                    String res = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_KZ_URL, JSONObject.toJSONString(weaveKz), Convert.toStr(CacheUtils.get("token")));
                    if (!StringUtils.isEmpty(res)) {
                        json = JSONObject.parseObject(res);
                        SendMessageErr err = new SendMessageErr();
                        err.setStatus(json.get("state").toString());
                        err.setBillNo(weaveKz.getSerialNo());
                        err.setErrMessage(json.get("message").toString());
                        err.setMethod("syncKzWeavereport2Mes");
                        err.setSendNode("开织报工");
                        if (Convert.toBool(json.get("state"))) {
                            log.info("发送开织报工数据成功，共{}，第：{}条。{}", list.size(), i, res);
                            syncDataService.updateWeaveKz(weaveKz);
                            syncDataService.isExistUpdate(err);
                        } else {
                            log.info("发送开织报工数据失败，共{}，第：{}条。{}", list.size(), i, res);
                            syncDataService.updateWeaveKz_N(weaveKz);
                            syncDataService.isExistUpdateAndAdd(err);
                        }
                    } else {
                        log.info("调用开织报工接口失败，共{}，第：{}条。{}", list.size(), i, res);
                    }
                } catch (Exception e) {
                    log.info("发送开织报工数据失败，共{}，第：{}条。{}", list.size(), i, e);
                }
            }
            log.info("结束发送开织报工数据，共：{}", list.size());
        } else {
            log.info("没有需要同步的开织数据");
        }
        return json;
    }
    /**
     * 下机报工
     */
    public JSONObject syncXjWeavereport2Mes(WeaveXj  weaveXj1) {
        List<WeaveXj> list = syncDataService.queryWeaveXjList(weaveXj1);
        List<User> userList = syncDataService.queryUserList("66");
        JSONObject json = new JSONObject();
        if (null != list && list.size() > 0) {
            log.info("开始发送下机报工数据，共：{}", list.size());
            for (int i = 0; i < list.size(); i++) {
                WeaveXj weaveXj = list.get(i);

                ArrayList<OperatorInfo> operatorInfoList = new ArrayList<OperatorInfo>();
                for (User user : userList) {
                    if (user.getUserCode().equals(weaveXj.getReporterAccount())) {
                        OperatorInfo operatorInfo = new OperatorInfo();
                        operatorInfo.setOperatorAccount(weaveXj.getReporterAccount());
                        operatorInfo.setTeamName(weaveXj.getBanZu());
                        operatorInfo.setTeamShift("");
                        operatorInfo.setQuantity(0.0);
                        operatorInfoList.add(operatorInfo);
                    }
                }
                weaveXj.setOperatorInfoList(operatorInfoList);
                log.info("发送下机报工数据，共{}，第：{}条。{}", list.size(), i, JSONObject.toJSONString(weaveXj));
                try {
                    if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                    String res = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_JJ_URL, JSONObject.toJSONString(weaveXj), Convert.toStr(CacheUtils.get("token")));
                    if (!StringUtils.isEmpty(res)) {
                        json = JSONObject.parseObject(res);
                        SendMessageErr err = new SendMessageErr();
                        err.setStatus(json.get("state").toString());
                        err.setBillNo(weaveXj.getSerialNo());
                        err.setErrMessage(json.get("message").toString());
                        err.setMethod("syncXjWeavereport2Mes");
                        err.setSendNode("下机报工");
                        if (Convert.toBool(json.get("state"))) {
                            log.info("发送下机报工数据成功，共{}，第：{}条。{}", list.size(), i, res);
                            syncDataService.updateWeaveXj(weaveXj);
                            syncDataService.isExistUpdate(err);
                        } else {
                            weaveXj.Sync_Message = "[下机]"+ json.get("message").toString();
                            syncDataService.updateWeaveXj_N(weaveXj);
                            syncDataService.isExistUpdateAndAdd(err);
                            log.info("发送下机报工数据失败，共{}，第：{}条。{}", list.size(), i, res);
                        }
                    } else {
                        log.info("调用下机报工接口失败，共{}，第：{}条。{}", list.size(), i, res);
                    }
                } catch (Exception e) {
                    log.info("发送下机报工数据失败，共{}，第：{}条。{}", list.size(), i, e);
                }
                WeaveReport reportZj = new WeaveReport();
                reportZj.setOrgId("66");

                reportZj.setSerialNo(weaveXj.getSerialNo());
                reportZj.setWarpBeamStatus("2");
                sysncZjWeavereport2Mes(reportZj);
            }
            log.info("结束发送下机报工数据，共：{}", list.size());

        } else {
            log.info("没有需要同步的下机数据");
        }
        return json;
    }

    /**
     * 穿综报工
     */
    public JSONObject syncCzWeavereport2Mes(WeaveCz weaveCz) {

        List<WeaveCz> list = syncDataService.queryWeaveCzList(weaveCz);
        List<User> userList = syncDataService.queryUserList(orgId);
        JSONObject json = new JSONObject();
        if (null != list && list.size() > 0) {
            log.info("开始同步穿综报工数据,总数：{}", list.size());
            for (int i = 0; i < list.size(); i++) {
                WeaveCz weaveCz1 = list.get(i);
                Double yield = Convert.toDouble(weaveCz1.getYield());
                ArrayList<OperatorInfo2B> operatorInfos = new ArrayList<>();
                if (weaveCz1.getChuanZongRen() != null) {
                    String[] reportor = weaveCz1.getChuanZongRen().split(";");
                    for (String str : reportor) {
                        for (int t = 0; t < userList.size(); t++) {
                            User user = userList.get(t);
                            if (str.equals(user.getUserName())) {
                                if(user.getUserDepart().equals("穿综")){
                                    OperatorInfo2B operatorInfo = new OperatorInfo2B();
                                    operatorInfo.setOperatorAccount(user.getUserCode());
                                    operatorInfo.setTeamName(weaveCz1.teamName);
                                    operatorInfo.setTeamShift(weaveCz1.teamShift);

                                    int floor =(int)Math.round((yield / reportor.length));
                                    operatorInfo.setQuantity(floor);
                                    operatorInfos.add(operatorInfo);
                                }
                            }
                        }
                    }
                }

                weaveCz1.setOperatorInfoList(operatorInfos);
                weaveCz1.setOrgId(orgId);

                log.info("发送穿综报工数据，共{}，第：{}条。{}", list.size(), i, JSONObject.toJSONString(weaveCz1));
                try {
                    if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                    String res = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_CZ_URL, JSONObject.toJSONString(weaveCz1), Convert.toStr(CacheUtils.get("token")));
                    if (!StringUtils.isEmpty(res)) {
                        json = JSONObject.parseObject(res);
                        SendMessageErr err = new SendMessageErr();
                        err.setStatus(json.get("state").toString());
                        err.setBillNo(weaveCz1.getSerialNo());
                        err.setErrMessage(json.get("message").toString());
                        err.setMethod("syncCzWeavereport2Mes");
                        err.setSendNode("穿综报工");
                        if (Convert.toBool(json.get("state"))) {
                            log.info("发送穿综报工数据成功，共{}，第：{}条。{}", list.size(), i, res);
                            syncDataService.updateWeaveCz(weaveCz1);
                            syncDataService.isExistUpdate(err);
                        } else {
                            log.info("发送穿综报工失败，共{}，第：{}条。{}", list.size(), i, res);
                            log.info("异常参数{}", JSONObject.toJSONString(weaveCz1));
                            weaveCz1.SyncMessage = "[穿综]"+ json.get("message").toString();
                            syncDataService.updateWeaveCz_N(weaveCz1);
                            syncDataService.isExistUpdateAndAdd(err);

                        }
                    } else {
                        log.info("调用穿综报工接口失败，共{}，第：{}条。{}", list.size(), i, res);
                    }
                } catch (Exception e) {
                    log.info("发送穿综报工数据第{}条错误:{}", i, e.getMessage());
                }
            }
        } else {
            log.info("没有需要同步的穿综数据：{}", list.size());
        }
        return json;
    }

    /**
     * 落布报工
     */
    public JSONObject syncLbWeavereport2Mes(WeaveLb weaveLb ) {
        JSONObject json = new JSONObject();
        List<WeaveLb> list = syncDataService.queryWeaveLbList(weaveLb);
        List<User> userList = syncDataService.queryUserList(orgId);
        if (null != list && list.size() > 0) {
            log.info("开始同步落布报工数据,总数：{}", list.size());
            for (int i = 0; i < list.size(); i++) {
                WeaveLb w = list.get(i);
                ArrayList<OperatorInfo> operatorInfoList = new ArrayList<OperatorInfo>();
                for (User user : userList) {
                    if (user.getUserCode().equals(w.getReporterAccount())) {
                        OperatorInfo operatorInfo = new OperatorInfo();
                        operatorInfo.setOperatorAccount(w.getReporterAccount());
                        operatorInfo.setTeamName(user.getUserDepart());
                        operatorInfo.setTeamShift("");
                        operatorInfo.setQuantity(0.0);
                        operatorInfoList.add(operatorInfo);
                    }
                }
                w.setOperatorInfoList(operatorInfoList);
                log.info("发送落布报工数据，共{}，第：{}条。{}", list.size(), i, JSONObject.toJSONString(w));
                try {
                    if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                    String res = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_LB_URL, JSONObject.toJSONString(w), Convert.toStr(CacheUtils.get("token")));
                    if (!StringUtils.isEmpty(res)) {
                        json = JSONObject.parseObject(res);
                        SendMessageErr err = new SendMessageErr();
                        err.setStatus(json.get("state").toString());
                        err.setBillNo(weaveLb.getSerialNo());
                        err.setErrMessage(json.get("message").toString());
                        err.setMethod("syncLbWeavereport2Mes");
                        err.setSendNode("落布报工");
                        if (Convert.toBool(json.get("state"))) {
                            log.info("发送落布报工数据成功，共{}，第：{}条。{}", list.size(), i, res);
                            syncDataService.updateWeaveLb(w);
                            syncDataService.isExistUpdate(err);
                        } else {
                            w.setSync_Message("[落布]"+json.get("message").toString());
                            syncDataService.updateWeaveLb_N(w);
                            syncDataService.isExistUpdateAndAdd(err);

                            log.info("发送落布报工失败，共{}，第：{}条。{}", list.size(), i, res);
                        }
                    } else {
                        log.info("调用落布报工接口失败，共{}，第：{}条。{}", list.size(), i, res);
                    }
                } catch (Exception e) {
                    log.info("发送落布报工数据第{}条错误:{}", i, e.getMessage());
                }
            }
        } else {
            log.info("没有需要同步的落布数据：{}", list.size());
        }
        return json;
    }


    //下班报工
    public void syncXbWeavereport2Mes(String orgId) {
        WeaveXb weaveLb = new WeaveXb();
        List<WeaveXb> list = syncDataService.queryWeaveXbList(orgId);
        List<User> userList = syncDataService.queryUserList(orgId);
        if (null != list && list.size() > 0) {
            log.info("开始同步下班数据,总数：{}", list.size());
            for (int i = 0; i < list.size(); i++) {
                WeaveXb weaveXb = list.get(i);
                log.info("发送下班报工数据，共{}，第：{}条。{}", list.size(), i, JSONObject.toJSONString(weaveXb));
                try {
                    XbInfo xbInfo = new XbInfo();
                    xbInfo.setMachineNo(weaveXb.getMachineNo());
                    ArrayList<XbInfo> xbInfos = new ArrayList<>();
                    ArrayList<OperatorInfo> operatorInfos = new ArrayList<>();
                    for (User user : userList) {
                        if (user.getUserName().equals(weaveXb.getReporterAccount())) {
                            OperatorInfo operatorInfo = new OperatorInfo();
                            operatorInfo.setOperatorAccount(user.getUserCode());
                            operatorInfo.setTeamName(weaveXb.getTeamName());
                            operatorInfo.setTeamShift(weaveXb.teamShift);
                            operatorInfos.add(operatorInfo);
                        }
                    }
                    weaveXb.setXbInfoList(xbInfos);
                    weaveXb.setOperatorInfoList(operatorInfos);
                    if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                    String res = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_XB_URL, JSONObject.toJSONString(weaveXb), Convert.toStr(CacheUtils.get("token")));
                    if (!StringUtils.isEmpty(res)) {
                        JSONObject json = JSONObject.parseObject(res);
                        if (Convert.toBool(json.get("state"))) {
                            log.info("发送下班报工数据成功，共{}，第：{}条。{}", list.size(), i, res);
                            weaveXb.setEAttribute5("Y");
                            syncDataService.updateWeaveXb(weaveXb);
                        } else {
                            weaveXb.setEAttribute5("N");
                            weaveXb.setEAttribute6(json.toString());
                            syncDataService.updateWeaveXb(weaveXb);
                            log.info("发送下班报工失败，共{}，第：{}条。{}", list.size(), i, res);
                        }
                    } else {
                        log.info("调用下班报工接口失败，共{}，第：{}条。{}", list.size(), i, res);
                    }
                } catch (Exception e) {
                    log.info("发送下班报工数据第{}条错误:{}", i, e.getMessage());
                }
            }
        } else {
            log.info("没有需要下班的落布数据：{}", list.size());
        }
    }

    //织布产量
    public void syncZBCLWeavereport2Mes(String orgId) {
        //请求机台监控数据
        LocalDate yesterDay = LocalDate.now().minusDays(1);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String yesterDate = yesterDay.format(dateTimeFormatter);
        String res = HttpUtils.sendGet(SyncConstants.JTJK_CLBB_GET_URL + "?classDate=" + yesterDate, null);
        if (!StringUtils.isEmpty(res)) {
            JSONObject jsonObject = JSONObject.parseObject(res);

            String msg = jsonObject.get("msg").toString();
            if (msg != null && msg.equals("success")) {
//                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    String data = jsonObject.get("data").toString();
                    log.info("织布产量机台监控接收到的数据=====" + msg);
                    List<Res_Data> list1 = JSONUtil.toList(data, Res_Data.class);
                    //映射对象
                    List<List<WeaveZBCL>> lists = convertObject(list1);//返回发送织布产量对象
                    int n = 0;
                    for (List<WeaveZBCL> list : lists) {
                        log.info("织布产量要发送的数据条数=====" + list.size());
                        log.info("织布产量要发送的数据=====" + JSONObject.toJSONString(list));
                        n++;
                        if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                        String post = HttpUtils.yqs_sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_ZBCL_URL, JSONObject.toJSONString(list), Convert.toStr(CacheUtils.get("token")));
                        if (!StringUtils.isEmpty(post)) {
                            JSONObject json = JSONObject.parseObject(post);
                            if (Convert.toBool(json.get("state"))) {
                                log.info("发送落布织布产量数据成功，共{}，第：{}条。{}", list.size(), n, post);
                            } else {
                                log.info("发送落布织布产量数据异常，共{}，第：{}条。{}", list.size(), n, post);
                            }
                        } else {
                            log.info("调用织布产量接口失败，共{}，第：{}条。{}", list.size(), n, post);
                        }
                    }
                } catch (Exception e) {
                    log.info(e.getMessage());
                }
            }
        }
    }

    public List<List<WeaveZBCL>> convertObject(List<Res_Data> resDatas) {
        ArrayList<WeaveZBCL> weaveZBCLS = new ArrayList<WeaveZBCL>();
        for (Res_Data resData : resDatas) {
            WeaveZBCL weaveZBCL = new WeaveZBCL();
            weaveZBCL.setRequestId(resData.getUuid());//请求id
            weaveZBCL.setSourcePk(resData.getUuid());//主键
            weaveZBCL.setDesignNo(resData.getGreyLot());//批号

            String greyNo = resData.getGreyNo();
            String[] splits = greyNo.split("/");
            weaveZBCL.setQualityNo(splits[0]);//品号
            weaveZBCL.setColorNo(splits[1]);//色号
            weaveZBCL.setQuantity(resData.getFabricLen());
            weaveZBCL.setProductionUnitName(resData.getRoomName());
            weaveZBCL.setTeamName(resData.getClassName());
            weaveZBCL.setUserName(resData.getStaffName());
            weaveZBCL.setMachineNo(resData.getMachNo());
            weaveZBCL.setProcessNo(resData.getMoName());
            weaveZBCL.setWorkingTime(resData.getClassDate());
            weaveZBCLS.add(weaveZBCL);
        }
        ArrayList<List<WeaveZBCL>> lists = new ArrayList<>();
        ArrayList<WeaveZBCL> weaveZBCLS1 = new ArrayList<>();
        for (int i = 0; i < weaveZBCLS.size(); i++) {
            weaveZBCLS1.add(weaveZBCLS.get(i));
            if (weaveZBCLS1.size() == 200) {
                lists.add(weaveZBCLS1);
                weaveZBCLS1.clear();
            }
        }
        return lists;
    }

    //挑轴记录回传
    public void syncDataTZRecord() {
        try {
            List<WeaveTZ> weaveTZS = syncDataService.queryTzRecord();
            if (weaveTZS.size() <= 0) {
                log.info("weaveTZS==" + weaveTZS.size());
                return;
            }
            if (weaveTZS.size() > 200) {
                for (int i = 0; i < weaveTZS.size(); i += 200) {
                    List<WeaveTZ> weaveTZS1 = weaveTZS.subList(i, i + 200);
                    if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                    String post = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_TZ_RECORD_URL, JSONObject.toJSONString(weaveTZS1), Convert.toStr(CacheUtils.get("token")));
                    if (!StringUtils.isEmpty(post)) {
                        JSONObject json = JSONObject.parseObject(post);
                        if (Convert.toBool(json.get("state"))) {
                            updateJZ(weaveTZS1, "Y");
                            log.info("发送挑轴数据成功，共{}，{}", weaveTZS.size(), json);
                        } else {
                            log.info("发送挑轴数据异常，共{}，{}", weaveTZS.size(), json);
                            updateJZ(weaveTZS1, "N");
                        }
                    } else {
                        log.info("调用挑轴接口失败，共{}，第：{}条", weaveTZS.size());
                    }
                }

            } else {
                if (ObjectUtils.isEmpty(CacheUtils.get("token"))) getToken();
                String post = HttpUtils.sendPost(SyncConstants.BASE_URL + SyncConstants.WEAVEREPORT_TZ_RECORD_URL, JSONObject.toJSONString(weaveTZS), Convert.toStr(CacheUtils.get("token")));
                if (!StringUtils.isEmpty(post)) {
                    JSONObject json = JSONObject.parseObject(post);
                    if (Convert.toBool(json.get("state"))) {
                        log.info("发送挑轴数据成功，共{}，第： 响应{}", weaveTZS.size(), json);
                        updateJZ(weaveTZS, "Y");
                    } else {
                        log.info("发送挑轴数据异常，共{}  响应{}", weaveTZS.size(), json);
                        updateJZ(weaveTZS, "N");
                    }
                } else {
                    log.info("调用挑轴接口失败，共{}，第：{}条", weaveTZS.size());
                }
            }
            for (WeaveTZ weaveTZ:weaveTZS){
                WeaveReport reportZj = new WeaveReport();
                reportZj.setOrgId("66");
                reportZj.setSerialNo(weaveTZ.getOldShaftCardNo());
                reportZj.setWarpBeamStatus("2");
                sysncZjWeavereport2Mes(reportZj);
            }

        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    void updateJZ(List<WeaveTZ> weaveTZS, String type) {
        for (WeaveTZ tz : weaveTZS) {
            tz.setResponseResult(type);
            int i = syncDataService.updateJZ(tz);
            log.info("剪轴记录更新状态 id{} 更新行数{}", tz.getSourcePk(), i);
        }
    }

}
